﻿using Dto;
using IBLL;
using IDAL;
using Model;

namespace BLL
{
    public class MemberBLL : IMemberBLL
    {
        public MemberBLL(IMemberDAL<MembersModel>dal,IMemberDAL<StateModel>sdal)
        {
            Dal = dal;
            Sdal = sdal;
        }

        public IMemberDAL<MembersModel> Dal { get; }
        public IMemberDAL<StateModel> Sdal { get; }

        public Task<int> AddMember(MembersModel members)
        {
            Random random= new Random();
            string code=random.Next(100,1000).ToString();
            members.Bh = DateTime.Now.ToString("yyyyMMddHHmmssff") + code;
            return Dal.AddAsync(members);
        }

        public Task<int> DeleteMember(int id)
        {
            var s=Dal.GetAllMember().FirstOrDefault(x => x.Id == id);
            s.IsDelete = true;
            return Dal.UpdateAsync(s);
        }

        public MembersModel Ft(int id)
        {
            return Dal.GetAllMember().FirstOrDefault(a => a.Id == id);
        }

        public MemberShowDto MemberShow(int pageindex, int pagesize)
        {
            var a = Dal.GetAllMember().Where(a=>a.IsDelete==false);
            var b = Sdal.GetAllMember();
            var sql = from c in a
                      join d in b on c.sid equals d.Sid
                      select new 
                      {
                          c.Id,
                          c.Bh,
                          c.Name,
                          c.Password,
                          c.BirthDay,
                          c.Img,
                          c.Age,
                          c.sid,
                          c.Sex,
                          c.IsDelete,
                          d.StateName
                      };
            int s=sql.Count();
            var m=sql.OrderBy(a=>a.Id).Skip((pageindex-1)*pagesize).Take(pagesize);
            return new MemberShowDto { Count=s,Members=m };
        }

        public Task<int> UpdateMember(MembersModel members)
        {
            return Dal.UpdateAsync(members);
        }
    }
}
